﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.Configuration;
using System.Net;
using System.ServiceModel.Activation;
using System.Web.Routing;
using ISC.MapDotNetServer.Core.Services;
using Microsoft.WindowsAzure.ServiceRuntime;
using OI.Web.RSS;

namespace OI.Web
{
    public class Global : System.Web.HttpApplication
    {
        public static string OIConnectionString { get; set; }
        public static string BingServiceKey { get; set; }
 
        void Application_Start(object sender, EventArgs e)
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 8;

            // UX Services need this to start up
            ResourceManager.Startup();

            // REST routes
            RouteTable.Routes.Add(new ServiceRoute("REST/9.0/Map", new WebServiceHostFactory(), typeof(ISC.MapDotNetServer.Services.MapDotNetServerWCFHost.REST.Map)));
            RouteTable.Routes.Add(new ServiceRoute("RSSFeed", new WebServiceHostFactory(), typeof(RSSFeed)));
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown
            ResourceManager.Shutdown();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            LoadConfig();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ResourceManager.OnBeginRequest(sender);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        private void LoadConfig()
        {
            if (ConfigurationManager.ConnectionStrings != null)
            {
                OIConnectionString = ConfigurationManager.ConnectionStrings["OIConnectionString"].ConnectionString;
            }

            if (ConfigurationManager.AppSettings != null)
            {
                BingServiceKey = ConfigurationManager.AppSettings["BingServiceKey"];
            }

            // override with Azure config if available
            if (RoleEnvironment.IsAvailable)
            {
                OIConnectionString = RoleEnvironment.GetConfigurationSettingValue("OIConnectionString");
                BingServiceKey = RoleEnvironment.GetConfigurationSettingValue("BingServiceKey");
            }
        }
    }
}